<!--
 * @Author: wuyue
 * @Date: 2023-02-23 15:20:50
 * @LastEditTime: 2023-03-10 18:01:55
 * @LastEditors: wuyue
 * @Descripttion: 
 * @version: 
-->
<template>
  <base-breadcrumb :title="$route.meta.title">
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel !==0 ? rules : {}"
      id="base-breadcrumb"
      style="position: relative"
    >
      <a-spin :spinning="loading">
        <!-- 计量设备调拨表单 -->
        <allocate-form :form="form" :editModel="editModel" :equipmentArr="equipmentArr" />
        <!-- 计量设备调拨清单 -->
        <allocate-log v-if="editModel === 0" />
        <!-- 页脚操作栏 -->
        <div class="btn_box page-btn-right-top">
          <a-button :loading="loading" :disabled="loading" v-if="editModel !== 0" type="primary" class="button_right" @click="handleSubmit(0)"
            >保存草稿</a-button>
          <a-button :loading="loading" :disabled="loading" v-if="editModel !== 0" type="primary" class="button_right" @click="handleSubmit(1)"
            >提交</a-button>
          <a-button v-if="checkVisibleInDetail" type="primary" @click="handleActiveClose">关闭</a-button>
        </div>
      </a-spin>
    </a-form-model>
  </base-breadcrumb>
</template>

<script>
import allocateForm from '@/views/quality/equipmentManagement/meterageEquipmentAllocate/components/allocateForm'
import { saveDraft, commit, detailsItem} from '@/api/quality/meterageEquipmentAllocate'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import moment from 'moment';
import allocateLog from '@/views/quality/equipmentManagement/meterageEquipmentAllocate/components/allocateLog'
import equipmentNameManagement from '@/api/quality/equipmentNameManagement' // api

export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: { allocateForm, allocateLog},
  data() {
    return {
      loading: false, // 提交按钮loding
      editModel: 2, // 操作状态:0 查看;1 编辑;2 新增
      equipmentArr: [],
      form: {
        fillInTime: moment().locale('zh-cn').format('YYYY-MM-DD 00:00:00'),
        inventoryList: [],
      }, // 表单
      rules: {
        transferInUnit: [{ required: true, message: '请选择调入单位', trigger: 'change' }],
        transferCompleteTime: [{ required: true, message: '请选择调拨完成时间', trigger: 'change' }],
      }
    }
  },
  async created() {
    const query = this.$route.query
    this.form.transferInUnit  = query.projectId
    this.editModel = Number(query.editModel)
    await this.getEquipmentArr()
    // 不为添加时请求详情
    if (this.editModel !== 2) {
      this.loading = true
      detailsItem({
        id: this.id
      }).then((res) => {
        this.loading = false
        this.form = res.data
        this.form.inventoryList.forEach(item => {
          let row = this.equipmentArr.find(i => i.id === item.mdId)
          // 设置规格型号的值
          item.specificationModelArr = row ? row.list : []
        })
        // 如果是待提交获取当前登录人信息
        if (this.form.transferState === '0') {
          this.getUserInfo() 
        }
      }).catch(() => {
        this.loading = false
      })
    } else {
        this.getUserInfo()
    }
  },
  methods: {
    // 获取登录用户的信息
    getUserInfo() {
      const userInfo = this.$userInfo()
      this.form.fillInUserId = userInfo.id
      this.form.fillInUserName = userInfo.name  
    },
    // 获取设备数组
    async getEquipmentArr() {
      const params = {
        param: { status: 0 },
        pageNum: 1,
        pageSize: 0
      }
      let res = await equipmentNameManagement.list(params)
      if (res.code === '0') {
          this.equipmentArr = res.data.list || []
      }
    },
    // 验证计量设备调拨清单是否填完完整
    validateInventoryList() {
      if (!this.form.inventoryList.length) {
          this.$message.warning('请添加计量设备调拨申请单')
          return false
      }
      for(let [index,v] of this.form.inventoryList.entries()) {
        let key = {
          mdId: '设备名称',
          mdModelId: '规格型号',
          applyNum:' 申请个数'
        }
        for(let i in v) {
          if (!v[i] && key[i]) {
              this.$message.warning(`第${index+1}行${key[i]}不能为空`)
              return false
          }
        }
      }
      return true
    },
    /**
     * 提交表单
     */
    handleSubmit(val) {
      let url = val === 0 ? saveDraft :  commit// 根据操作切换url地址
      // 校验表单
      this.$refs.ruleForm.validate((e) => {
        if (e) {
          if (!this.validateInventoryList()) return;
          // 提交表单
          this.loading = true
          let form = this.$clone(this.form)
          url(form)
            .then((res) => {
              this.loading = false
              if (res.code === '0' || res.data.code === '0') {
                this.$message.success('提交成功！')
                this.$multiTab.close()
              }
            })
            .catch(() => {
              this.loading = false
            })
        }
      })
    }
  }
}
</script>